package com.funo.wcity.app.service.mail;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.mail.Folder;
import javax.mail.Message;

import org.springframework.stereotype.Service;

import com.funo.wcity.app.dao.TblContactPersonsDAO;
import com.funo.wcity.app.dao.TblIpMailDAO;
import com.funo.wcity.app.dao.TblMailAnnexDAO;
import com.funo.wcity.app.dao.TblMailDetailDAO;
import com.funo.wcity.app.entity.TblContactPersons;
import com.funo.wcity.app.entity.TblIpMail;
import com.funo.wcity.app.entity.TblMailAnnex;
import com.funo.wcity.app.entity.TblMailDetail;
import com.funo.wcity.app.service.mail.receive.ReceiveMail;
import com.funo.wcity.app.service.mail.send.MailBean;
import com.funo.wcity.app.service.mail.send.MailConstant;
import com.funo.wcity.app.utils.Constant;
import com.funo.wcity.app.utils.PubFile;
import com.funo.wcity.app.utils.StringUtil;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.pop3.POP3Folder;

/**
 * 类说明：接收邮件服务层及分析保存
 * 
 * @author 作者: 李刚
 * @version 创建时间：2011-8-2 下午11:45:41
 */
@Service("receiveMailService")
public class ReceiveMailService {
	@Resource(name="tblMailDetailDAO")
	private TblMailDetailDAO tblMailDetailDAO;
	@Resource(name="tblMailAnnexDAO")
	private TblMailAnnexDAO tblMailAnnexDAO;
	@Resource(name="tblContactPersonsDAO")
	private TblContactPersonsDAO tblContactPersonsDAO;
	@Resource(name="tblIpMailDAO")
	private TblIpMailDAO tblIpMailDAO;
	private ReceiveMail receiveMail;
	/**
	 * 解析邮件
	 * @param
	 * 		folderType
	 * 			1收件夹；2草稿箱；3已发送；4已删除；5垃圾邮件
	 * @param
	 * 		receiveMail
	 * 			接收电子邮件对象
	 * @param
	 * 		idUser
	 * 			用户id
	 * @param
	 * 		path
	 * 			绝对路径
	 * @param
	 * 		contextPath
	 * 			上下文项目
	 * @param
	 * 		mailType
	 * 			1IMAP；2POP3
	 */
	public void getAnalMail(int folderType,ReceiveMail receiveMail,Integer idUser,String path,String contextPath,Integer mailType) throws Exception {
		this.receiveMail = receiveMail;
		if (1 == mailType) {
			IMAPFolder folder = this.receiveMail.openImapFolder(folderType(folderType), Folder.READ_WRITE);
			// 获取服务所有messageUID
			long[] longAttr = this.receiveMail.getImapMessageUIDs(folder);
			if (longAttr == null)return;
			// 获取本地所有messageUID,格式：,***,**,
			String messageUidStr = this.tblMailDetailDAO.getMessageUid(idUser);
			for (int i = 0; i < longAttr.length; i++) {
				// 不存在获取邮件信息
				if (messageUidStr.indexOf("," + longAttr[i] + ",") == -1) {
					MailBean mailBean = this.receiveMail.getMessageByUID(longAttr[i]);
					// 公司类型id，公司id，联系人id
					String idCompanyType = "", idCompany = "", idContactPerson = "";
					// 拆分发件人
					String from = mailBean.getFromAddress();
					if (!StringUtil.isEmpty(from)) {
						if (from.indexOf("<") > -1) {
							from = from.substring(from.indexOf("<") + 1, from.indexOf(">"));
						}
					}
					// 通过发件人邮箱查询联系人信息
					TblContactPersons tblContactPersons = this.tblContactPersonsDAO.getTblContactPersons(from);
					if (tblContactPersons != null) {
						idCompanyType = ",";
						idCompany = ",";
						idContactPerson = ",";
						idContactPerson += tblContactPersons.getIdContactPerson()+ ",";
						idCompany += tblContactPersons.getTblcompanies().getIdCompany()+ ",";
						idCompanyType += tblContactPersons.getTblcompanies().getIdCompanyType()+ ",";
					}
					TblMailDetail tblMailDetail = new TblMailDetail();
					tblMailDetail.setIdCompanyType(idCompanyType);
					tblMailDetail.setIdCompany(idCompany);
					tblMailDetail.setIdContactPerson(idContactPerson);
					tblMailDetail.setMessageUid(String.valueOf(mailBean.getMessageUid()));
					tblMailDetail.setIdUser(idUser);
					tblMailDetail.setCopySend(StringUtil.getMailBoxRule(StringUtil.reTrimByString(mailBean.getToCc()).replace("\r\n", "").replace("\r", "").replace("\n", "").replaceAll(" ", "")));
					tblMailDetail.setSecretSend(StringUtil.getMailBoxRule(StringUtil.reTrimByString(mailBean.getToBcc()).replace("\r\n", "").replace("\r", "").replace("\n", "").replaceAll(" ", "")));
					tblMailDetail.setRecPeople(StringUtil.getMailBoxRule(StringUtil.reTrimByString(mailBean.getToAddress()).replace("\r\n", "").replace("\r", "").replace("\n", "").replaceAll(" ", "")));
					tblMailDetail.setSendPeople(StringUtil.getMailBoxRule(StringUtil.reTrimByString(mailBean.getFromAddress()).replace("\r\n","").replace("\r", "").replace("\n", "").replaceAll(" ", "")));
					// 解析附件
					tblMailDetail.setIdMailAnnex(ResFile(mailBean.getContent(),mailBean.getFileNames(), mailBean.getMessageUid(),path));
					// 1已读标志，0未读标志
					tblMailDetail.setMailSign(0);
					tblMailDetail.setTitle(mailBean.getSubject());
					tblMailDetail.setShortContent(ResContent(mailBean.getContent()));
					// 解析内容
					tblMailDetail.setContent(ResContent(mailBean.getContent(),tblMailDetail.getIdMailAnnex(), path, contextPath));
					tblMailDetail.setState(folderType);
					// 来信识别IP与地区
					if (!StringUtil.isEmpty(mailBean.getMailIp())) {
						String[] idAttr = mailBean.getMailIp().split("\\.");
						StringBuffer sb = new StringBuffer();
						for (int j = 0; j < idAttr.length; j++) {
							if (idAttr[j].length() == 1) {
								sb.append("00").append(idAttr[j]);
							} else if (idAttr[j].length() == 2) {
								sb.append("0").append(idAttr[j]);
							} else {
								sb.append(idAttr[j]);
							}
						}
						List<TblIpMail> tblIpMailList = this.tblIpMailDAO.getTblIpMailList(Long.valueOf(sb.toString()));
						if (tblIpMailList.size() > 0) {
							TblIpMail tblIpMail = tblIpMailList.get(0);
							tblMailDetail.setIpCompany(tblIpMail.getCompany());
							tblMailDetail.setIpCountry(tblIpMail.getCountry());
						}
					}
					tblMailDetail.setLastDate(mailBean.getMailDate());
					this.tblMailDetailDAO.save(tblMailDetail);
				}
			}
		} else if (2 == mailType) {
			POP3Folder folder = this.receiveMail.openPop3Folder(folderType(folderType), Folder.READ_WRITE);
			//获取服务所有messageUID
			Message[] messages = folder.getMessages();
			//获取本地所有messageUID,格式：,***,**,
			String messageUidStr = this.tblMailDetailDAO.getMessageUid(idUser);
			for(int i=0;i<messages.length;i++){
				 Message message = messages[i];
	             //验证此邮件是否存在
	             String uid=folder.getUID(message);
	             //不存在获取邮件信息
	  			if(messageUidStr.indexOf(","+uid+",")==-1){
	  				MailBean mailBean=this.receiveMail.setPop3MailBean(message);
					//公司类型id，公司id，联系人id
					String idCompanyType="",idCompany="",idContactPerson="";
					//拆分发件人
					String from =mailBean.getFromAddress();
					if(!StringUtil.isEmpty(from)){
						if(from.indexOf("<")>-1){
							from=from.substring(from.indexOf("<")+1, from.indexOf(">"));
						}
					}
					//通过发件人邮箱查询联系人信息
					TblContactPersons tblContactPersons=this.tblContactPersonsDAO.getTblContactPersons(from);
					if(tblContactPersons!=null){
						idCompanyType=",";idCompany=",";idContactPerson=",";
						idContactPerson+=tblContactPersons.getIdContactPerson()+",";
						idCompany+=tblContactPersons.getTblcompanies().getIdCompany()+",";
						idCompanyType+=tblContactPersons.getTblcompanies().getIdCompanyType()+",";
					}
					TblMailDetail tblMailDetail=new TblMailDetail();
					tblMailDetail.setIdCompanyType(idCompanyType);
					tblMailDetail.setIdCompany(idCompany);
					tblMailDetail.setIdContactPerson(idContactPerson);
					tblMailDetail.setMessageUid(uid);
					tblMailDetail.setIdUser(idUser);
					tblMailDetail.setCopySend(StringUtil.getMailBoxRule(StringUtil.reTrimByString(mailBean.getToCc()).replace("\r\n", "").replace("\r", "").replace("\n", "").replaceAll(" ", "")));
					tblMailDetail.setSecretSend(StringUtil.getMailBoxRule(StringUtil.reTrimByString(mailBean.getToBcc()).replace("\r\n", "").replace("\r", "").replace("\n", "").replaceAll(" ", "")));
					tblMailDetail.setRecPeople(StringUtil.getMailBoxRule(StringUtil.reTrimByString(mailBean.getToAddress()).replace("\r\n", "").replace("\r", "").replace("\n", "").replaceAll(" ", "")));
					tblMailDetail.setSendPeople(StringUtil.getMailBoxRule(StringUtil.reTrimByString(mailBean.getFromAddress()).replace("\r\n", "").replace("\r", "").replace("\n", "").replaceAll(" ", "")));
					//解析附件
					tblMailDetail.setIdMailAnnex(ResFile(mailBean.getContent(),mailBean.getFileNames(),message,path));
					//1已读标志，0未读标志
					tblMailDetail.setMailSign(0);
					tblMailDetail.setTitle(mailBean.getSubject());
					tblMailDetail.setShortContent(ResContent(mailBean.getContent()));
					//解析内容
					tblMailDetail.setContent(ResContent(mailBean.getContent(),tblMailDetail.getIdMailAnnex(),path,contextPath));
					tblMailDetail.setState(folderType);
					//来信识别IP与地区
					if(!StringUtil.isEmpty(mailBean.getMailIp())){
						String[] idAttr=mailBean.getMailIp().split("\\.");
						StringBuffer sb=new StringBuffer();
						for(int j=0;j<idAttr.length;j++){
							 if(idAttr[j].length()==1){
								 sb.append("00").append(idAttr[j]);
							 }else if(idAttr[j].length()==2){
								 sb.append("0").append(idAttr[j]);
							 }else{
								 sb.append(idAttr[j]);
							 }
						 }
						List<TblIpMail> tblIpMailList=this.tblIpMailDAO.getTblIpMailList(Long.valueOf(sb.toString()));
						if(tblIpMailList.size()>0){
							TblIpMail tblIpMail=tblIpMailList.get(0);
							tblMailDetail.setIpCompany(tblIpMail.getCompany());
							tblMailDetail.setIpCountry(tblIpMail.getCountry());
						}
					}
					tblMailDetail.setLastDate(mailBean.getMailDate());
					this.tblMailDetailDAO.save(tblMailDetail);
	  			}
			}
		}
	}

	// 根据邮件夹类型设置邮件夹的名称
	public static String folderType(int type) {
		switch (type) {
		case MailConstant.INBOX:
			return MailConstant.FOLDER_INBOX;
		case MailConstant.DRAFT:
			return MailConstant.FOLDER_DRAFT;
		case MailConstant.DELETE:
			return MailConstant.FOLDER_DELETE;
		case MailConstant.SENDED:
			return MailConstant.FOLDER_SENDED;
		case MailConstant.SPAM:
			return MailConstant.FOLDER_SPAM;
		}
		return MailConstant.FOLDER_INBOX;
	}
	//解析附件及保存
	public String ResFile(String content,String fileNames,long messageByUid,String path){
		StringBuffer sb=new StringBuffer();
		try{
			if(!StringUtil.isEmpty(fileNames)){
				if(!StringUtil.isEmpty(content)){
					String[] fileNameAttr=fileNames.split("\\,");
					for(int i=0;i<fileNameAttr.length;i++){
						TblMailAnnex tblMailAnnex=new TblMailAnnex();
						//文件夹名称
						String floder=System.currentTimeMillis()+i+"/";
						String filePath=path+floder;
						this.receiveMail.createLocalImapFile(messageByUid,true,fileNameAttr[i],filePath);
						//映射Bean
						tblMailAnnex.setFilename(floder+fileNameAttr[i]);
						//1 附件，2嵌入附件
						tblMailAnnex.setStatus(1);
						Date date=new Date();
						date.setTime(date.getTime()+i);
						tblMailAnnex.setLastDate(date);
						sb.append(this.tblMailAnnexDAO.save(tblMailAnnex));
						sb.append(",");
					}
				}else{
					String[] fileNameAttr=fileNames.split("\\,");
					for(int i=0;i<fileNameAttr.length;i++){
						TblMailAnnex tblMailAnnex=new TblMailAnnex();
						//文件夹名称
						String floder=System.currentTimeMillis()+i+"/";;
						String filePath=path+floder;
						this.receiveMail.createLocalImapFile(messageByUid,true,fileNameAttr[i],filePath);
						tblMailAnnex.setFilename(floder+fileNameAttr[i]);
						//1 附件，2嵌入附件
						tblMailAnnex.setStatus(1);
						Date date=new Date();
						date.setTime(date.getTime()+i);
						tblMailAnnex.setLastDate(date);
						sb.append(this.tblMailAnnexDAO.save(tblMailAnnex));
						sb.append(",");
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return sb.length()>0?sb.substring(0, sb.length()-1):"";
	}
	//解析附件及保存
	public String ResFile(String content,String fileNames,Message message,String path){
		StringBuffer sb=new StringBuffer();
		try{
			if(!StringUtil.isEmpty(fileNames)){
				if(!StringUtil.isEmpty(content)){
					String[] fileNameAttr=fileNames.split("\\,");
					for(int i=0;i<fileNameAttr.length;i++){
						TblMailAnnex tblMailAnnex=new TblMailAnnex();
						//文件夹名称
						String floder=System.currentTimeMillis()+i+"/";
						String filePath=path+floder;
						this.receiveMail.createLocalPop3File(message,true,fileNameAttr[i],filePath);
						//映射Bean
						tblMailAnnex.setFilename(floder+fileNameAttr[i]);
						//1 附件，2嵌入附件
						tblMailAnnex.setStatus(1);
						tblMailAnnex.setLastDate(new Date());
						sb.append(this.tblMailAnnexDAO.save(tblMailAnnex));
						sb.append(",");
					}
				}else{
					String[] fileNameAttr=fileNames.split("\\,");
					for(int i=0;i<fileNameAttr.length;i++){
						TblMailAnnex tblMailAnnex=new TblMailAnnex();
						//文件夹名称
						String floder=System.currentTimeMillis()+i+"/";;
						String filePath=path+floder;
						this.receiveMail.createLocalPop3File(message,true,fileNameAttr[i],filePath);
						tblMailAnnex.setFilename(floder+fileNameAttr[i]);
						//1 附件，2嵌入附件
						tblMailAnnex.setStatus(1);
						tblMailAnnex.setLastDate(new Date());
						sb.append(this.tblMailAnnexDAO.save(tblMailAnnex));
						sb.append(",");
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return sb.length()>0?sb.substring(0, sb.length()-1):"";
	}
	//解析内容
	public String ResContent(String content,String idMailAnnex,String path,String contextPath){
		System.out.println("==========================邮件内容："+content);
		if(!StringUtil.isEmpty(content)){
			//查询邮件附件
			if(!StringUtil.isEmpty(idMailAnnex)){
				List<TblMailAnnex>  mailAnnexList=this.tblMailAnnexDAO.getTblMailAnnexList(idMailAnnex,null);
				int i=0;
				for(TblMailAnnex tblMailAnnex:mailAnnexList){
					if(content.indexOf("src=\"cid:")>-1){
						//获取数据库文件名
						String fileName=tblMailAnnex.getFilename();
						//获取文件名
						String name=fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
						//获取跟文件夹
						String floder=fileName.substring(0,fileName.lastIndexOf("/"));
						//获取扩展名
						String dot=name.substring(name.lastIndexOf("."),name.length());
						PubFile pubFile=new PubFile(path+"/"+floder,name);
						//新的文件名
						String newname=System.currentTimeMillis()+i+"";
						try {
							pubFile.renameFile(newname);
						} catch (Exception e) {
							e.printStackTrace();
						}
						String newFileName=fileName.replace(name,newname+dot);
						tblMailAnnex.setFilename(newFileName);
						//为嵌入式文件
						tblMailAnnex.setStatus(2);
						//修改附件信息
						this.tblMailAnnexDAO.update(tblMailAnnex);
			    		String temp=content.substring(content.indexOf("src=\"cid:")+5,content.indexOf("\"", content.indexOf("src=\"cid:")+5));
			    		content=content.replace(temp, contextPath+Constant.PATH+tblMailAnnex.getFilename());
			    		i++;
			    	}else{
			    		break;
			    	}
				}
			}
		}
		return content;
	}
	//解析文本内容
	public String ResContent(String content){
		if(!StringUtil.isEmpty(content)){
			Integer length=content.length();
			if(length>12){
				content=content.substring(0, 12)+"...";
			}
			//获取如果有图片，图片标签去掉。
			if(content.indexOf("<img")>-1){
				content=content.substring(0, content.indexOf("<img"));
			}
		}
		return content;
	}
}
